﻿using GlennQuigmire.API.Application.GDtos;
using IMES.Common.Domain.SirModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;

namespace GlennQuigmire.API.Application.Commands
{
    public class InboundOrderSearchHander : IRequestHandler<InboundOrderSearchCommand, ResultT<InboundOrderListDto>>
    {

        private readonly IBaseRepositorys<InboundOrderType> inboundOrderTypeRepository;
        private readonly IBaseRepositorys<InboundOrder> inboundOrderRepository;
        public InboundOrderSearchHander(IBaseRepositorys<InboundOrderType> inboundOrderTypeRepository, IBaseRepositorys<InboundOrder> inboundOrderRepository)
        {
            this.inboundOrderTypeRepository = inboundOrderTypeRepository;
            this.inboundOrderRepository = inboundOrderRepository;
        }

        /// <summary>
        /// 查询入库单（入库单显示）
        /// </summary>
        /// <param name="request">查询入库单请求对象</param>
        /// <param name="cancellationToken">允许取消异步</param>
        /// <returns>查询入库单响应对象</returns>
        public Task<ResultT<InboundOrderListDto>> Handle(InboundOrderSearchCommand request, CancellationToken cancellationToken)
        {
            var result = new ResultT<InboundOrderListDto>();

            var list = (from a in inboundOrderRepository.GetAll().Where(c=>!c.DeleteDate)
                       join b in inboundOrderTypeRepository.GetAll() on a.InboundOrderTypeId equals b.InboundOrderTypeId
                       select new InboundOrderListDto
                       {
                           InboundOrderId = a.InboundOrderId,
                           InboundOrderNumber = a.InboundOrderNumber,
                           InboundOrderTypeId = a.InboundOrderTypeId,
                           Remark = a.Remark,
                           InboundOrderDate = a.InboundOrderDate.ToString("yyyy-MM-dd HH:mm:ss"),
                           CreateId = a.CreateId,
                           CreateDate=a.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                           CreateName=a.CreateName,
                           UpdateId = a.UpdateId,
                           UpdateDate = a.UpdateDate,
                           UpdateName = a.UpdateName,
                           InboundOrderTypeName = b.InboundOrderTypeName
                       }).ToList();
            if(!string.IsNullOrEmpty(request.InboundOrderNumber))
            {
                list = list.Where(c => c.InboundOrderNumber.Contains(request.InboundOrderNumber)).ToList();
            }

            result.Data = list;
            return Task.FromResult(result);
        }
    }
}
